

#include <stdint.h>
#include <string.h>
#include "rfid_interface.h"
//滤波器宽度，等于载波（125KHz）周期的采样点数量
#define FILTER_WIDTH		(RFID_ITF_COLLECT_FREQ / 125000U)

typedef struct {
	uint32_t sum;
	uint16_t buf[FILTER_WIDTH];
	uint8_t index;
	uint8_t setuped;
}AvgFilter_T;


void AvgFilter_Init(AvgFilter_T* filter){
	memset(filter, 0, sizeof(*filter));
}

void AvgFilter_Setup(AvgFilter_T* filter, const uint16_t val[2]){
	filter->sum = 0;
	for(int i = 0; i < FILTER_WIDTH; i++){
		filter->buf[i] += val[i];
		filter->sum += val[i];
	}
	filter->index = 0;
	filter->setuped = 1;
}

static void AvgFilter_DoFiltering(AvgFilter_T* filter, const uint16_t* input, uint32_t length, uint16_t* output){
	const uint16_t* pInput = input;
	uint16_t* pOutput = output;
	uint32_t len = length;
	uint16_t quit;

	while(len != 0){
		len--;
		const int16_t in = *pInput++;
		*pOutput = filter->sum / FILTER_WIDTH;
		pOutput++;
		quit = filter->buf[filter->index];
		filter->buf[filter->index++] = in;
		if(filter->index >= FILTER_WIDTH){
			filter->index = 0;
		}
		filter->sum = filter->sum + in - quit;
	}
}


static AvgFilter_T avgFilter;

uint32_t AvgFilter_Filtering(uint16_t *adcValue, uint32_t length){
	uint32_t outlen;
	
	if(!avgFilter.setuped){
		outlen = length - FILTER_WIDTH;
		AvgFilter_Setup(&avgFilter, adcValue);
		AvgFilter_DoFiltering(&avgFilter, adcValue + FILTER_WIDTH, outlen, adcValue);
	}
	else{
		outlen = length;
		AvgFilter_DoFiltering(&avgFilter, adcValue, outlen, adcValue);
	}
	
	return outlen;
}

